#include <algorithm>
#include <iostream>
#include "Master.h"
#include "TwoWayList.cc"

using namespace std;

enum {rock = 0, paper = 1, scissors = 2};

MasterImp::MasterImp()
#ifdef DEBUG_EVPROC
: EventProcessorImp(true,"Master") // comment to remove debug
#endif
{
  // register the message function

  RegisterMessageProcessor(DieMessage::type, &Die, 0 /* priority */);

  RegisterMessageProcessor(ChoiceMessage::type, &ChoiceMade, 1 /* priority */);

  RegisterMessageProcessor(PlayDoneMessage::type, &GameOver, 2 /* priority */);
  p1 = -1;
		  
}

void MasterImp::MakeDecision(int p2, EventProcessor& sender){

	if(p1 == rock) 
	{
		if(p2 == rock)
		{
			//deadlock
			PlayAgain(sender);
		}
		else if(p2 == paper){
			//p2 is winner
			KillEvProc(Player1);
			KillEvProc(sender);
		}
		else if(p2 == scissors){
			//p1 is winner
			KillEvProc(sender);
			KillEvProc(Player1);
		} 	
	}
	else if(p1 == paper){
		
		if(p2 == paper)
		{
			//deadlock
			PlayAgain(sender);
		}
		else if(p2 == scissors){
			//p2 is winner 
			KillEvProc(Player1);
			KillEvProc(sender);
		}
		else if(p2 == rock){
			//p1 is winner
			KillEvProc(sender);
			KillEvProc(Player1);
		} 	
	}
	 		
	else if(p1 == scissors){
		
		if(p2 == scissors)
		{
			//deadlock
			PlayAgain(sender);
		}
		else if(p2 == rock){
			//p2 is winner 
			KillEvProc(Player1);
			KillEvProc(sender);
		}
		else if(p2 == paper){
			//p1 is winner
			KillEvProc(sender);
			KillEvProc(Player1);
		} 	
	}
}
void MasterImp::PlayAgain(EventProcessor& sender){
	
	p1 = -1;	

	EventProcessor myInterfClone1;
	myInterfClone1.CopyFrom(myInterface);
	PlayAgainMessage_Factory(Player1,1,myInterfClone1);

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);
	PlayAgainMessage_Factory(sender,1,myInterfClone);
}

MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, GameOver, PlayDoneMessage)
		
		evProc.Seppuku();
		
MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, ChoiceMade, ChoiceMessage)

	if(evProc.p1 == -1)
	{
		evProc.p1 = msg.choice;
		evProc.Player1.CopyFrom(msg.sender);
	}
	else{
		evProc.MakeDecision(msg.choice,msg.sender);
	}

MESSAGE_HANDLER_DEFINITION_END


MESSAGE_HANDLER_DEFINITION_BEGIN(MasterImp, Die, DieMessage)

	evProc.EventProcessorImp::processDieMessage(evProc,msg);

MESSAGE_HANDLER_DEFINITION_END

